# -*- coding: utf-8 -*-
import sys
import requests
import os
import time

def from_file(download_place,download_name):
	if (download_place == "local"):
		if(os.access(download_name,os.R_OK)):
			return True
		else:
			return False
	elif (download_place == "internet"):
		test = requests.get(download_name)
		if (test.status_code == requests.codes.ok):
			return True
		else:
			return False
	else:
		return False

def save_file(save_file):
	try:
		test = open(save_file,"wb")
		test.close()
		os.remove(save_file)
	except:
		return False
	return True

def download(download_place,download_name,save_file):
	if (os.access(save_file,os.F_OK)):
		os.remove(save_file)
	download_list = []
	download_save = ""
	if (download_place == "internet"):
		r = requests.get(download_name)
		if (r.status_code != requests.codes.ok):
			print("源文件错误")
			return False
		with open("$tmp$.m3u8","w") as w:
			for chunk in r.iter_content(chunk_size=1024):
				if chunk:
					w.write(chunk)
		download_name = "$tmp$.m3u8"
	with open(download_name,"r") as r:
		chunk = r.readline()
		while chunk:
			if (chunk[0] != '#'):
				download_list.append(chunk)
			chunk = r.readline()
	download_nums = len(download_list)
	download_ok_nums = 0
	errors = 0
	while (download_ok_nums != download_nums):
		print("\rComplete:%d/%d" %(download_ok_nums,download_nums),end = "")
		r = requests.get(download_list[download_ok_nums])
		if (r.status_code == requests.codes.ok):
			with open(save_file,"ab") as w:
				for i in r.iter_content(i_size=1024):
					if i:
						w.write(i)
		else:
			errors += 1
		download_ok_nums += 1
		time.sleep(0.1)
	print("\rComplete:%d/%d" %(download_ok_nums,download_nums),end = "")
	print("\n下载完成")
	print("错误数量:%d" % errors)

if __name__ == "__main__":
	data = sys.argv
	if (len(data) != 4):
		print("参数不正确")
	elif (data[1] != "local" and data[1] != "internet"):
		print("参数不正确")
	elif (not from_file(data[1],data[2])):
		print("源文件错误")
	elif (not save_file(data[3])):
		print("目标文件无法写入")
	else:
		download(data[1],data[2],data[3])